package org.session.util;

import java.util.concurrent.CountDownLatch;

/**
 * ThreadTimer provides an easy way to track time spent by thread(s) doing
 * work(s).
 * 
 * Reference - Java Concurrency In Practice, Listing 5.11 TestHarness
 */
public final class ThreadTimer {
    public static long timeThreads(final Runnable threadWork, int threadCount)
            throws InterruptedException {
        final CountDownLatch startGate = new CountDownLatch(1);
        final CountDownLatch endGate = new CountDownLatch(threadCount);

        for (int iter = 0; iter < threadCount; iter++) {
            Thread workerThread = new Thread() {
                public void run() {
                    try {
                        startGate.await();
                        try {
                            threadWork.run();
                        } finally {
                            endGate.countDown();
                        }
                    } catch (InterruptedException interruptedException) {
                        // do nothing
                    }
                }
            };

            workerThread.start();
        }

        long startTimeNanos = System.nanoTime();
        startGate.countDown();
        endGate.await();
        long endTimeNanos = System.nanoTime();
        long elapsedNanos = endTimeNanos - startTimeNanos;

        return elapsedNanos;
    }

    // Prevent instance escape at all costs
    private ThreadTimer() {
    }

}